package com.wsjc.common.redis.sentinels;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;

import com.wsjc.common.core.config.JedisConfig;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * java版哨兵
 * 
 * @author 93733
 *
 */
public class JedisJavaSentinels {

	static String master;
	// 所有 slave
	static final Vector<String> slaveRedisServers = new Vector<String>();
	// 坏掉的实例
	static final Vector<String> badRedisServers = new Vector<String>();
	
	static JedisPool jedisPool ;
	
	@Autowired
	private  JedisPoolConfig jedisPoolConfig ;
	
	volatile static JedisJavaSentinels jedisJavaSentinels ;
	
	public static synchronized JedisJavaSentinels getInstance(boolean javaSentinelOpenStatus){
		if(null == jedisJavaSentinels){
			jedisJavaSentinels = new JedisJavaSentinels(JedisConfig.readConfig("redis.sentinel.master.address"), javaSentinelOpenStatus ) ;
		}
		return jedisJavaSentinels ;
	}
	

	private JedisJavaSentinels(String masterAddress , boolean javaSentinelOpenStatus) {
		
		// 是否开启java哨兵
		if(javaSentinelOpenStatus){
			// 配置 redis master
	        //config("127.0.0.1:6380");
			config(masterAddress);
			// 定时任务
			new Timer().schedule(new TimerTask() {
				@Override
				public void run() {
					// 检测 master是否可以
					checkMaster();
					// 更新slave列表
					updateSlaves();
					// 检测坏掉的实例是否恢复正常
					checkBadServer();

				}
			}, 1000L, 3000L);
		}
		
		String[] serverInfo = masterAddress.split(":");
        String masterHost = serverInfo[0] ;
        int masterPort = Integer.parseInt(serverInfo[1]) ;
        jedisPool = new JedisPool(jedisPoolConfig, masterHost, masterPort, 100000 , JedisConfig.readConfig("redis.auth.password"));
		
	}

	/**
	 * 获取jedis 实例
	 * @param sentinelMaster
	 * @return
	 */
	public Jedis newJedisInstance() {
        return jedisPool.getResource() ;
	}

	private static void checkBadServer() {
		// 获取所有slave
		Iterator<String> iterator = badRedisServers.iterator();
		while (iterator.hasNext()) {
			String bad = iterator.next();
			try {
				String badHost = bad.split(":")[0];
				int badPort = Integer.parseInt(bad.split(":")[1]);
				Jedis badServer = new Jedis(badHost, badPort);
				badServer.ping();

				// 如果ping没有问题，则挂在当前的master
				badServer.slaveof(master.split(":")[0], Integer.parseInt(master.split(":")[1]));
				badServer.close();

				slaveRedisServers.add(bad);
				iterator.remove();
				System.out.println(bad + " 恢复正常，当前master:" + master);
			} catch (Exception e) {
			}
		}
	}

	private static void updateSlaves() {
		// 获取所有slave
		try {
			String masterHost = master.split(":")[0];
			int masterPort = Integer.parseInt(master.split(":")[1]);
			Jedis jedis = new Jedis(masterHost, masterPort);
			String info_replication = jedis.info("replication");
			// 解析info replication
			String[] lines = info_replication.split("\r\n");
			int slaveCount = Integer.parseInt(lines[2].split(":")[1]);
			if (slaveCount > 0) {
				slaveRedisServers.clear();
				for (int i = 0; i < slaveCount; i++) {
					String host = lines[3 + i].split(",")[0].split("=")[1];
					String port = lines[3 + i].split(",")[1].split("=")[1];
					slaveRedisServers.add(host + ":" + port);
				}
			}
			System.out.println("更新slave列表:" + Arrays.toString(slaveRedisServers.toArray(new String[] {})));
			jedis.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("更新slave失败:" + e.getMessage());
		}
	}

	private static void config(String ms) {
		master = ms;
	}

	private static void checkMaster() {
		// 主从切换
		// 检查状态
		System.out.println("检查master状态:" + master);
		String masterHost = master.split(":")[0];
		int masterPort = Integer.parseInt(master.split(":")[1]);
		try {
			Jedis jedis = new Jedis(masterHost, masterPort);
			jedis.ping();
			jedis.close();
		} catch (Exception e) {
			// master挂掉啦
			badRedisServers.add(master);
			// 切换master
			changeMaster();
		}
	}

	/** 切换master */
	private static void changeMaster() {
		Iterator<String> iterator = slaveRedisServers.iterator();
		while (iterator.hasNext()) {
			String slave = iterator.next();
			try {
				String slaveHost = slave.split(":")[0];
				int slavePort = Integer.parseInt(slave.split(":")[1]);
				Jedis jedis = new Jedis(slaveHost, slavePort);
				jedis.slaveofNoOne();
				jedis.close();
				master = slave;
				System.out.println("产生新的master:" + master);
				break;
			} catch (Exception e) {
				badRedisServers.add(slave);
			} finally {
				iterator.remove();
			}
		}

		// 所有slave切到新的master
		for (String slave : slaveRedisServers) {
			String slaveHost = slave.split(":")[0];
			int slavePort = Integer.parseInt(slave.split(":")[1]);
			Jedis jedis = new Jedis(slaveHost, slavePort);
			jedis.slaveof(master.split(":")[0], Integer.parseInt(master.split(":")[1]));

			jedis.close();
		}
	}

}
